using ExcelLibrary.SpreadSheet;
using ResxHelper.Object;
using System.IO;

namespace ResxHelper.Logic.Readers
{
    public class ExcelResourceFileReader : IResourceFileReader
    {
        public string Path { get; private set; }
        private Workbook _workbook;

        public ExcelResourceFileReader(string path)
        {
            Path = path;
        }

        public ResourceFile Read()
        {
            if (!File.Exists(Path)) return null;

            ReadFile(Path);
            if (_workbook == null) return null;

            var resourceFile = new ResourceFile {FilePath = Path, CultureInfo = ResourceFile.ReadCulture(Path)};

            resourceFile = ParseEntries(resourceFile);
            return resourceFile;
        }

        private ResourceFile ParseEntries(ResourceFile file)
        {
            var sheet = _workbook.Worksheets[0];

            for (var i = sheet.Cells.FirstRowIndex; i <= sheet.Cells.LastRowIndex; i++)
            {
                var entry = new ResourceFileEntry();
                var row = sheet.Cells.GetRow(i);
                entry.Key = row.GetCell(0).Value.ToString();
                entry.Value = row.GetCell(1).Value.ToString();
                entry.Comment = row.GetCell(2) == Cell.EmptyCell ? string.Empty : row.GetCell(2).Value.ToString();
                file.Entries.Add(entry.Key, entry);
            }
            return file;
        }

        private void ReadFile(string path)
        {
            _workbook = Workbook.Load(path);
        }
    }
}
